import profile
import datetime
from django.template import RequestContext
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from waivers.models import Waiver, UserWaiver
from django.contrib.auth.models import User

def getSignedWaiverIDs(user_id):
    user = User.objects.get(pk=user_id)
    query = UserWaiver.objects.filter(user=user)
    ids = []
    for user_waiver in query:
        waiver = user_waiver.waiver
        ids.append(waiver.id)
    return ids

def getUnsignedWaiverLinks(user_id):
    user_waivers = getSignedWaiverIDs(user_id)
    waivers = Waiver.objects.all()
    req = []
    non = []
    for waiver in waivers:
        if waiver.required and waiver.id not in user_waivers:
            url = '<a href="/waivers/sign/' + str(waiver.id) +'">'
            url += waiver.name + "</a>"
            req.append(url)
        elif waiver.id not in user_waivers:
            url = '<a href="/waivers/sign/' + str(waiver.id) + '">'
            url += waiver.name + "</a>"
            non.append(url)
    return {"required":req, "not_required":non}

def getSignedWaiverLinks(user_id):
    user = User.objects.get(pk=user_id)
    query = UserWaiver.objects.filter(user=user)
    req = []
    non = []
    for user_waiver in query:
        waiver = user_waiver.waiver
        if waiver.required:
            url = '<a href="/waivers/view/' + str(waiver.id) + '/' + str(user_id) +'">'
            url += waiver.name + "</a>"
            req.append(url)
        else:
            url = '<a href="/waivers/view/' + str(waiver.id) + '/' + str(user_id) +'">'
            url += waiver.name + "</a>"
            non.append(url)
    return {"required":req, "not_required":non}

def listUnsigned(request, user_id):
    if request.user.id == user_id or request.user.is_staff or request.user.profile.gym_staff:
        links = getUnsignedWaiverLinks(user_id)
        return render_to_response("waivers/list.html",
            {'mode':'Unsigned', 'user':User.objects.get(pk=user_id),
            'required':links["required"], "not_required":links["not_required"]},
			context_instance=RequestContext(request))
    else:
        return render_to_response("unauth.html", {})

def listSigned(request, user_id):
    if request.user.id == user_id or request.user.is_staff or request.user.profile.gym_staff:
        links = getSignedWaiverLinks(user_id)
        return render_to_response("waivers/list.html",
            {'mode':'Signed', 'user':User.objects.get(pk=user_id),
            'required':links["required"], "not_required":links["not_required"]},
			context_instance=RequestContext(request))
    else:
        return render_to_response("unauth.html", {})

@login_required(login_url='accounts/login/')
def listSelf(request):
    return listSigned(request, request.user.id)

class sigForm(forms.Form):
    agree = forms.BooleanField(label="I have read and agree to the terms and conditions of this waiver ")
    signature = forms.CharField(label="Typed Signature", required=False, max_length=50)
    output = forms.CharField(label="output",required=False)

    def save(self, waiver, user):
        data = self.cleaned_data
        user_waiver = UserWaiver(user=user, waiver=waiver,
                        agree=data["agree"], signature=data["signature"], signature_json=data["output"])
        user_waiver.save()
        if waiver.required:
            user.is_active = True
            user.save()

    def check_for_errors(self, user, waiver):
        data = self.cleaned_data

        try:
            UserWaiver.objects.get(user = user, waiver = waiver)
        except UserWaiver.DoesNotExist:
            pass
        else:
            return 'Error: You have already signed this waiver.'

        if not data["agree"]:
            return "Error: You must agree to the terms and conditions of the waiver."
        elif len(data["signature"].strip()) == 0:
            return "Error: You must type your name in the signature field."
        elif len(data["output"].strip()) == 0:
            return "Error: you must sign the signature field."
        return ''

@login_required(login_url='accounts/login/')
def view(request, user_id, waiver_id):
    user = User.objects.get(pk=user_id)
    waiver = Waiver.objects.get(pk=waiver_id)
    user_waiver = UserWaiver.objects.get(user=user, waiver=waiver)
    return render_to_response("waivers/view.html",
                {'name' : waiver.name, 'content':waiver.content, 'waiver_sig':user_waiver.signature,
				'waiver_date':user_waiver.datetime,'waiver_json':user_waiver.signature_json},
				context_instance=RequestContext(request))

@login_required(login_url='accounts/login/')
def sign(request, waiver_id):
    user = request.user
    waiver = Waiver.objects.get(pk=waiver_id)
    message = ''
    if request.method == 'POST':
        form = sigForm(request.POST)
        if form.is_valid():
            message = form.check_for_errors(user, waiver)
            if len(message) == 0:
                form.save(waiver, user)
                return HttpResponseRedirect("/waivers/view/" + str(waiver.id) + "/" + str(user.id) )
    else:
        form = sigForm
    return render_to_response("waivers/sign.html", 
                {'name' : waiver.name, 'content':waiver.content, 'form':form,
                'message':message, 'csrf_token':csrf(request)['csrf_token']},
				context_instance=RequestContext(request))
